import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    userInfo: null,
    token: '',
    location: null,
    currentCity: '北京'
  },
  mutations: {
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
    },
    SET_TOKEN(state, token) {
      state.token = token
    },
    SET_LOCATION(state, location) {
      state.location = location
    },
    SET_CURRENT_CITY(state, city) {
      state.currentCity = city
    }
  },
  actions: {
    // 获取用户信息
    getUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        uni.getUserInfo({
          success: (res) => {
            commit('SET_USER_INFO', res.userInfo)
            resolve(res.userInfo)
          },
          fail: (err) => {
            reject(err)
          }
        })
      })
    },
    // 获取位置信息
    getLocation({ commit }) {
      return new Promise((resolve, reject) => {
        uni.getLocation({
          type: 'gcj02',
          success: (res) => {
            commit('SET_LOCATION', res)
            resolve(res)
          },
          fail: (err) => {
            reject(err)
          }
        })
      })
    }
  },
  getters: {
    isLogin: state => !!state.token,
    userInfo: state => state.userInfo,
    location: state => state.location,
    currentCity: state => state.currentCity
  }
})

export default store 